<template>
  <div ref="editor" :style="style"></div>
</template>

<script>
import ace from 'ace-builds'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/theme-monokai'

export default {
  name: 'AceEditor',
  props: {
    value: {
      type: String,
      required: true
    },
    lang: {
      type: String,
      default: 'sql'
    },
    theme: {
      type: String,
      default: 'monokai'
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      editor: null,
      style: {
        height: '500px',
        width: '100%'
      },
      completions: [
        'redshift',
        'spark',
        'flink'
      ]
    }
  },
  mounted() {
    this.editor = ace.edit(this.$refs.editor)
    this.editor.session.setMode(`ace/mode/${this.lang}`)
    this.editor.setTheme(`ace/theme/${this.theme}`)
    this.editor.setReadOnly(this.readOnly)
    this.editor.setValue(this.value, 1)
    // Apply the options
    this.editor.setOptions(this.options)
    this.editor.on('change', () => {
      const content = this.editor.getValue()
      this.$emit('input', content)
    })
    // Register custom completions
    const customCompleter = {
      getCompletions: (editor, session, pos, prefix, callback) => {
        if (prefix.length === 0) {
          return callback(null, [])
        }
        const completions = this.customCompletions.map(word => ({
          caption: word,
          value: word,
          meta: 'custom'
        }))
        callback(null, completions)
      }
    }

    // ace.require('ace/ext/language_tools').addCompleter(customCompleter)
  },
  methods: {

  },
  watch: {
    value(newValue) {
      if (newValue !== this.editor.getValue()) {
        this.editor.setValue(newValue, 1)
      }
    },
    lang(newLang) {
      this.editor.session.setMode(`ace/mode/${newLang}`)
    },
    theme(newTheme) {
      this.editor.setTheme(`ace/theme/${newTheme}`)
    },
    readOnly(newReadOnly) {
      this.editor.setReadOnly(newReadOnly)
    }
  },
  beforeDestroy() {
    this.editor.destroy()
  }
}
</script>

<style scoped>
.ace_editor .ace_active-line {
  /*color: #0caffe;*/
  background-color: #48ed08
}
</style>